{% extends 'base.html' %}
{% load static %}

{% block title %}用户管理 - CFS Web System{% endblock %}

{% block page_type %}users{% endblock %}

{% block breadcrumb_items %}
<li class="breadcrumb-item"><a href="{% url 'dashboard:dashboard' %}">仪表板</a></li>
<li class="breadcrumb-item"><a href="{% url 'settings:settings' %}">系统设置</a></li>
<li class="breadcrumb-item active">用户管理</li>
{% endblock %}

{% block content %}
<div class="row">
    <!-- 用户统计 -->
    <div class="col-12 mb-4">
        <div class="row g-3">
            <div class="col-md-3">
                <div class="card bg-primary text-white">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h6 class="card-title mb-0">总用户数</h6>
                                <h3 class="mb-0" id="total-users">0</h3>
                            </div>
                            <i class="fas fa-users fa-2x opacity-75"></i>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card bg-success text-white">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h6 class="card-title mb-0">活跃用户</h6>
                                <h3 class="mb-0" id="active-users">0</h3>
                            </div>
                            <i class="fas fa-user-check fa-2x opacity-75"></i>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card bg-warning text-white">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h6 class="card-title mb-0">管理员</h6>
                                <h3 class="mb-0" id="admin-users">0</h3>
                            </div>
                            <i class="fas fa-user-shield fa-2x opacity-75"></i>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card bg-info text-white">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h6 class="card-title mb-0">在线用户</h6>
                                <h3 class="mb-0" id="online-users">0</h3>
                            </div>
                            <i class="fas fa-circle fa-2x opacity-75"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 用户管理 -->
    <div class="col-12">
        <div class="card">
            <div class="card-header">
                <div class="d-flex justify-content-between align-items-center">
                    <h5 class="mb-0">
                        <i class="fas fa-users me-2"></i>用户列表
                    </h5>
                    <div class="d-flex gap-2">
                        <button type="button" class="btn btn-outline-secondary" onclick="refreshUsers()">
                            <i class="fas fa-sync-alt"></i> 刷新
                        </button>
                        <button type="button" class="btn btn-primary" onclick="addUser()">
                            <i class="fas fa-plus"></i> 添加用户
                        </button>
                    </div>
                </div>
            </div>
            
            <!-- 搜索和过滤 -->
            <div class="card-body border-bottom">
                <div class="row g-3">
                    <div class="col-md-4">
                        <div class="input-group">
                            <span class="input-group-text">
                                <i class="fas fa-search"></i>
                            </span>
                            <input type="text" class="form-control" id="search-users" placeholder="搜索用户名、邮箱...">
                        </div>
                    </div>
                    <div class="col-md-2">
                        <select class="form-select" id="filter-role">
                            <option value="">所有角色</option>
                            <option value="admin">管理员</option>
                            <option value="user">普通用户</option>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <select class="form-select" id="filter-status">
                            <option value="">所有状态</option>
                            <option value="active">活跃</option>
                            <option value="inactive">非活跃</option>
                            <option value="locked">锁定</option>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <select class="form-select" id="sort-by">
                            <option value="created_at">创建时间</option>
                            <option value="last_login">最后登录</option>
                            <option value="username">用户名</option>
                            <option value="email">邮箱</option>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <div class="d-flex gap-1">
                            <button type="button" class="btn btn-outline-secondary" onclick="clearFilters()">
                                <i class="fas fa-times"></i>
                            </button>
                            <button type="button" class="btn btn-outline-primary" onclick="exportUsers()">
                                <i class="fas fa-download"></i>
                            </button>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- 用户列表 -->
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-hover mb-0">
                        <thead class="table-light">
                            <tr>
                                <th>
                                    <div class="form-check">
                                        <input class="form-check-input" type="checkbox" id="select-all-users">
                                    </div>
                                </th>
                                <th>用户</th>
                                <th>角色</th>
                                <th>状态</th>
                                <th>最后登录</th>
                                <th>创建时间</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody id="users-table-body">
                            <!-- 用户列表将动态加载 -->
                        </tbody>
                    </table>
                </div>
                
                <!-- 分页 -->
                <div class="card-footer">
                    <div class="d-flex justify-content-between align-items-center">
                        <div class="text-muted">
                            显示 <span id="users-start">0</span> - <span id="users-end">0</span> 条，共 <span id="users-total">0</span> 条
                        </div>
                        <nav>
                            <ul class="pagination pagination-sm mb-0" id="users-pagination">
                                <!-- 分页将动态生成 -->
                            </ul>
                        </nav>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 添加/编辑用户模态框 -->
<div class="modal fade" id="userModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="userModalTitle">添加用户</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="user-form">
                <div class="modal-body">
                    <input type="hidden" id="user-id" name="user_id">
                    
                    <div class="row g-3">
                        <!-- 基本信息 -->
                        <div class="col-12">
                            <h6 class="border-bottom pb-2 mb-3">
                                <i class="fas fa-user me-2"></i>基本信息
                            </h6>
                        </div>
                        
                        <div class="col-md-6">
                            <label class="form-label">用户名 <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="username" name="username" required>
                        </div>
                        
                        <div class="col-md-6">
                            <label class="form-label">邮箱 <span class="text-danger">*</span></label>
                            <input type="email" class="form-control" id="email" name="email" required>
                        </div>
                        
                        <div class="col-md-6">
                            <label class="form-label">姓名</label>
                            <input type="text" class="form-control" id="first-name" name="first_name">
                        </div>
                        
                        <div class="col-md-6">
                            <label class="form-label">姓氏</label>
                            <input type="text" class="form-control" id="last-name" name="last_name">
                        </div>
                        
                        <div class="col-md-6">
                            <label class="form-label">电话</label>
                            <input type="tel" class="form-control" id="phone" name="phone">
                        </div>
                        
                        <div class="col-md-6">
                            <label class="form-label">部门</label>
                            <input type="text" class="form-control" id="department" name="department">
                        </div>
                        
                        <!-- 账户设置 -->
                        <div class="col-12">
                            <h6 class="border-bottom pb-2 mb-3 mt-3">
                                <i class="fas fa-cog me-2"></i>账户设置
                            </h6>
                        </div>
                        
                        <div class="col-md-6">
                            <label class="form-label">角色 <span class="text-danger">*</span></label>
                            <select class="form-select" id="role" name="role" required>
                                <option value="user">普通用户</option>
                                <option value="admin">管理员</option>
                            </select>
                        </div>
                        
                        <div class="col-md-6">
                            <label class="form-label">状态</label>
                            <select class="form-select" id="status" name="status">
                                <option value="active">活跃</option>
                                <option value="inactive">非活跃</option>
                                <option value="locked">锁定</option>
                            </select>
                        </div>
                        
                        <div class="col-md-6" id="password-field">
                            <label class="form-label">密码 <span class="text-danger">*</span></label>
                            <div class="input-group">
                                <input type="password" class="form-control" id="password" name="password">
                                <button type="button" class="btn btn-outline-secondary" onclick="togglePassword()">
                                    <i class="fas fa-eye" id="password-toggle-icon"></i>
                                </button>
                            </div>
                            <div class="form-text">密码至少8位，包含字母和数字</div>
                        </div>
                        
                        <div class="col-md-6" id="confirm-password-field">
                            <label class="form-label">确认密码 <span class="text-danger">*</span></label>
                            <input type="password" class="form-control" id="confirm-password" name="confirm_password">
                        </div>
                        
                        <!-- 权限设置 -->
                        <div class="col-12">
                            <h6 class="border-bottom pb-2 mb-3 mt-3">
                                <i class="fas fa-shield-alt me-2"></i>权限设置
                            </h6>
                        </div>
                        
                        <div class="col-12">
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-check">
                                        <input class="form-check-input" type="checkbox" id="can-upload" name="permissions" value="upload">
                                        <label class="form-check-label" for="can-upload">
                                            文件上传
                                        </label>
                                    </div>
                                    <div class="form-check">
                                        <input class="form-check-input" type="checkbox" id="can-download" name="permissions" value="download">
                                        <label class="form-check-label" for="can-download">
                                            文件下载
                                        </label>
                                    </div>
                                    <div class="form-check">
                                        <input class="form-check-input" type="checkbox" id="can-create-template" name="permissions" value="create_template">
                                        <label class="form-check-label" for="can-create-template">
                                            创建模板
                                        </label>
                                    </div>
                                    <div class="form-check">
                                        <input class="form-check-input" type="checkbox" id="can-edit-template" name="permissions" value="edit_template">
                                        <label class="form-check-label" for="can-edit-template">
                                            编辑模板
                                        </label>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-check">
                                        <input class="form-check-input" type="checkbox" id="can-delete-template" name="permissions" value="delete_template">
                                        <label class="form-check-label" for="can-delete-template">
                                            删除模板
                                        </label>
                                    </div>
                                    <div class="form-check">
                                        <input class="form-check-input" type="checkbox" id="can-view-logs" name="permissions" value="view_logs">
                                        <label class="form-check-label" for="can-view-logs">
                                            查看日志
                                        </label>
                                    </div>
                                    <div class="form-check">
                                        <input class="form-check-input" type="checkbox" id="can-manage-users" name="permissions" value="manage_users">
                                        <label class="form-check-label" for="can-manage-users">
                                            用户管理
                                        </label>
                                    </div>
                                    <div class="form-check">
                                        <input class="form-check-input" type="checkbox" id="can-system-settings" name="permissions" value="system_settings">
                                        <label class="form-check-label" for="can-system-settings">
                                            系统设置
                                        </label>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- 其他设置 -->
                        <div class="col-12">
                            <h6 class="border-bottom pb-2 mb-3 mt-3">
                                <i class="fas fa-sliders-h me-2"></i>其他设置
                            </h6>
                        </div>
                        
                        <div class="col-12">
                            <div class="form-check form-switch">
                                <input class="form-check-input" type="checkbox" id="email-notifications" name="email_notifications" checked>
                                <label class="form-check-label" for="email-notifications">
                                    邮件通知
                                </label>
                            </div>
                        </div>
                        
                        <div class="col-12">
                            <div class="form-check form-switch">
                                <input class="form-check-input" type="checkbox" id="force-password-change" name="force_password_change">
                                <label class="form-check-label" for="force-password-change">
                                    强制下次登录时修改密码
                                </label>
                            </div>
                        </div>
                        
                        <div class="col-12">
                            <label class="form-label">备注</label>
                            <textarea class="form-control" id="notes" name="notes" rows="3" placeholder="用户备注信息..."></textarea>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-save"></i> 保存
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- 用户详情模态框 -->
<div class="modal fade" id="userDetailModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">用户详情</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="user-detail-content">
                <!-- 用户详情内容将动态加载 -->
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" onclick="editUserFromDetail()">
                    <i class="fas fa-edit"></i> 编辑
                </button>
            </div>
        </div>
    </div>
</div>

<!-- 批量操作模态框 -->
<div class="modal fade" id="batchActionModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">批量操作</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <p>已选择 <span id="selected-count">0</span> 个用户</p>
                
                <div class="mb-3">
                    <label class="form-label">操作类型</label>
                    <select class="form-select" id="batch-action">
                        <option value="">请选择操作</option>
                        <option value="activate">激活用户</option>
                        <option value="deactivate">停用用户</option>
                        <option value="lock">锁定用户</option>
                        <option value="unlock">解锁用户</option>
                        <option value="reset_password">重置密码</option>
                        <option value="delete">删除用户</option>
                    </select>
                </div>
                
                <div class="alert alert-warning">
                    <i class="fas fa-exclamation-triangle me-2"></i>
                    批量操作将影响所选的所有用户，请谨慎操作。
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="executeBatchAction()">
                    <i class="fas fa-check"></i> 执行
                </button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
// 全局变量
let currentPage = 1;
let currentUserId = null;
let selectedUsers = new Set();

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    initializeUsersPage();
});

// 初始化用户管理页面
function initializeUsersPage() {
    // 加载用户统计
    loadUserStats();
    
    // 加载用户列表
    loadUsers();
    
    // 绑定事件
    bindEvents();
}

// 绑定事件
function bindEvents() {
    // 搜索框
    document.getElementById('search-users').addEventListener('input', debounce(loadUsers, 300));
    
    // 过滤器
    document.getElementById('filter-role').addEventListener('change', loadUsers);
    document.getElementById('filter-status').addEventListener('change', loadUsers);
    document.getElementById('sort-by').addEventListener('change', loadUsers);
    
    // 全选复选框
    document.getElementById('select-all-users').addEventListener('change', toggleSelectAll);
    
    // 表单提交
    document.getElementById('user-form').addEventListener('submit', saveUser);
    
    // 角色变更时更新权限
    document.getElementById('role').addEventListener('change', updatePermissionsByRole);
}

// 加载用户统计
function loadUserStats() {
    fetch('/settings/ajax/user-stats/')
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            document.getElementById('total-users').textContent = data.stats.total;
            document.getElementById('active-users').textContent = data.stats.active;
            document.getElementById('admin-users').textContent = data.stats.admin;
            document.getElementById('online-users').textContent = data.stats.online;
        }
    })
    .catch(error => {
        console.error('加载用户统计失败:', error);
    });
}

// 加载用户列表
function loadUsers(page = 1) {
    const params = new URLSearchParams({
        page: page,
        search: document.getElementById('search-users').value,
        role: document.getElementById('filter-role').value,
        status: document.getElementById('filter-status').value,
        sort: document.getElementById('sort-by').value
    });
    
    fetch(`/settings/ajax/users/?${params}`)
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            renderUsersList(data.users);
            renderPagination(data.pagination);
            updatePaginationInfo(data.pagination);
        }
    })
    .catch(error => {
        console.error('加载用户列表失败:', error);
    });
}

// 渲染用户列表
function renderUsersList(users) {
    const tbody = document.getElementById('users-table-body');
    
    if (users.length === 0) {
        tbody.innerHTML = `
            <tr>
                <td colspan="7" class="text-center py-4">
                    <div class="text-muted">
                        <i class="fas fa-users fa-3x mb-3"></i>
                        <p>暂无用户数据</p>
                    </div>
                </td>
            </tr>
        `;
        return;
    }
    
    tbody.innerHTML = users.map(user => `
        <tr>
            <td>
                <div class="form-check">
                    <input class="form-check-input user-checkbox" type="checkbox" value="${user.id}" onchange="updateSelectedUsers()">
                </div>
            </td>
            <td>
                <div class="d-flex align-items-center">
                    <div class="avatar-sm me-3">
                        <div class="avatar-title bg-primary rounded-circle">
                            ${user.username.charAt(0).toUpperCase()}
                        </div>
                    </div>
                    <div>
                        <h6 class="mb-0">${user.username}</h6>
                        <small class="text-muted">${user.email}</small>
                        ${user.full_name ? `<br><small class="text-muted">${user.full_name}</small>` : ''}
                    </div>
                </div>
            </td>
            <td>
                <span class="badge bg-${user.role === 'admin' ? 'warning' : 'secondary'}">
                    ${user.role === 'admin' ? '管理员' : '普通用户'}
                </span>
            </td>
            <td>
                <span class="badge bg-${getStatusColor(user.status)}">
                    ${getStatusText(user.status)}
                </span>
                ${user.is_online ? '<i class="fas fa-circle text-success ms-1" title="在线"></i>' : ''}
            </td>
            <td>
                <span class="text-muted">${user.last_login || '从未登录'}</span>
            </td>
            <td>
                <span class="text-muted">${user.created_at}</span>
            </td>
            <td>
                <div class="btn-group btn-group-sm">
                    <button type="button" class="btn btn-outline-primary" onclick="viewUser(${user.id})" title="查看">
                        <i class="fas fa-eye"></i>
                    </button>
                    <button type="button" class="btn btn-outline-secondary" onclick="editUser(${user.id})" title="编辑">
                        <i class="fas fa-edit"></i>
                    </button>
                    <div class="btn-group btn-group-sm">
                        <button type="button" class="btn btn-outline-secondary dropdown-toggle" data-bs-toggle="dropdown">
                            <i class="fas fa-ellipsis-v"></i>
                        </button>
                        <ul class="dropdown-menu">
                            <li><a class="dropdown-item" href="#" onclick="resetUserPassword(${user.id})"><i class="fas fa-key me-2"></i>重置密码</a></li>
                            <li><a class="dropdown-item" href="#" onclick="toggleUserStatus(${user.id}, '${user.status}')"><i class="fas fa-${user.status === 'active' ? 'ban' : 'check'} me-2"></i>${user.status === 'active' ? '停用' : '启用'}</a></li>
                            <li><hr class="dropdown-divider"></li>
                            <li><a class="dropdown-item text-danger" href="#" onclick="deleteUser(${user.id})"><i class="fas fa-trash me-2"></i>删除</a></li>
                        </ul>
                    </div>
                </div>
            </td>
        </tr>
    `).join('');
}

// 获取状态颜色
function getStatusColor(status) {
    const colors = {
        'active': 'success',
        'inactive': 'secondary',
        'locked': 'danger'
    };
    return colors[status] || 'secondary';
}

// 获取状态文本
function getStatusText(status) {
    const texts = {
        'active': '活跃',
        'inactive': '非活跃',
        'locked': '锁定'
    };
    return texts[status] || status;
}

// 渲染分页
function renderPagination(pagination) {
    const paginationEl = document.getElementById('users-pagination');
    
    if (pagination.total_pages <= 1) {
        paginationEl.innerHTML = '';
        return;
    }
    
    let html = '';
    
    // 上一页
    html += `
        <li class="page-item ${pagination.current_page === 1 ? 'disabled' : ''}">
            <a class="page-link" href="#" onclick="loadUsers(${pagination.current_page - 1})">
                <i class="fas fa-chevron-left"></i>
            </a>
        </li>
    `;
    
    // 页码
    for (let i = Math.max(1, pagination.current_page - 2); i <= Math.min(pagination.total_pages, pagination.current_page + 2); i++) {
        html += `
            <li class="page-item ${i === pagination.current_page ? 'active' : ''}">
                <a class="page-link" href="#" onclick="loadUsers(${i})">${i}</a>
            </li>
        `;
    }
    
    // 下一页
    html += `
        <li class="page-item ${pagination.current_page === pagination.total_pages ? 'disabled' : ''}">
            <a class="page-link" href="#" onclick="loadUsers(${pagination.current_page + 1})">
                <i class="fas fa-chevron-right"></i>
            </a>
        </li>
    `;
    
    paginationEl.innerHTML = html;
    currentPage = pagination.current_page;
}

// 更新分页信息
function updatePaginationInfo(pagination) {
    document.getElementById('users-start').textContent = pagination.start_index;
    document.getElementById('users-end').textContent = pagination.end_index;
    document.getElementById('users-total').textContent = pagination.total_count;
}

// 添加用户
function addUser() {
    currentUserId = null;
    document.getElementById('userModalTitle').textContent = '添加用户';
    document.getElementById('user-form').reset();
    
    // 显示密码字段
    document.getElementById('password-field').style.display = 'block';
    document.getElementById('confirm-password-field').style.display = 'block';
    document.getElementById('password').required = true;
    document.getElementById('confirm-password').required = true;
    
    // 设置默认权限
    updatePermissionsByRole();
    
    const modal = new bootstrap.Modal(document.getElementById('userModal'));
    modal.show();
}

// 编辑用户
function editUser(userId) {
    currentUserId = userId;
    document.getElementById('userModalTitle').textContent = '编辑用户';
    
    // 隐藏密码字段
    document.getElementById('password-field').style.display = 'none';
    document.getElementById('confirm-password-field').style.display = 'none';
    document.getElementById('password').required = false;
    document.getElementById('confirm-password').required = false;
    
    // 加载用户数据
    fetch(`/settings/ajax/users/${userId}/`)
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            populateUserForm(data.user);
            
            const modal = new bootstrap.Modal(document.getElementById('userModal'));
            modal.show();
        }
    })
    .catch(error => {
        console.error('加载用户数据失败:', error);
    });
}

// 填充用户表单
function populateUserForm(user) {
    document.getElementById('user-id').value = user.id;
    document.getElementById('username').value = user.username;
    document.getElementById('email').value = user.email;
    document.getElementById('first-name').value = user.first_name || '';
    document.getElementById('last-name').value = user.last_name || '';
    document.getElementById('phone').value = user.phone || '';
    document.getElementById('department').value = user.department || '';
    document.getElementById('role').value = user.role;
    document.getElementById('status').value = user.status;
    document.getElementById('email-notifications').checked = user.email_notifications;
    document.getElementById('force-password-change').checked = user.force_password_change;
    document.getElementById('notes').value = user.notes || '';
    
    // 设置权限
    document.querySelectorAll('input[name="permissions"]').forEach(checkbox => {
        checkbox.checked = user.permissions.includes(checkbox.value);
    });
}

// 根据角色更新权限
function updatePermissionsByRole() {
    const role = document.getElementById('role').value;
    const permissions = document.querySelectorAll('input[name="permissions"]');
    
    if (role === 'admin') {
        permissions.forEach(checkbox => {
            checkbox.checked = true;
        });
    } else {
        // 普通用户默认权限
        const defaultPermissions = ['upload', 'download'];
        permissions.forEach(checkbox => {
            checkbox.checked = defaultPermissions.includes(checkbox.value);
        });
    }
}

// 保存用户
function saveUser(event) {
    event.preventDefault();
    
    const formData = new FormData(event.target);
    
    // 验证密码
    if (document.getElementById('password').required) {
        const password = formData.get('password');
        const confirmPassword = formData.get('confirm_password');
        
        if (password !== confirmPassword) {
            CFS.utils.showNotification('密码确认不匹配', 'error');
            return;
        }
        
        if (password.length < 8) {
            CFS.utils.showNotification('密码至少8位', 'error');
            return;
        }
    }
    
    // 处理权限
    const permissions = [];
    document.querySelectorAll('input[name="permissions"]:checked').forEach(checkbox => {
        permissions.push(checkbox.value);
    });
    formData.delete('permissions');
    formData.append('permissions', JSON.stringify(permissions));
    
    const url = currentUserId ? `/settings/ajax/users/${currentUserId}/update/` : '/settings/ajax/users/create/';
    
    CFS.utils.showLoading(true);
    
    fetch(url, {
        method: 'POST',
        body: formData,
        headers: {
            'X-CSRFToken': CFS.utils.getCsrfToken()
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            CFS.utils.showNotification(currentUserId ? '用户更新成功' : '用户创建成功', 'success');
            
            // 关闭模态框
            const modal = bootstrap.Modal.getInstance(document.getElementById('userModal'));
            modal.hide();
            
            // 重新加载列表
            loadUsers(currentPage);
            loadUserStats();
        } else {
            CFS.utils.showNotification(data.message || '操作失败', 'error');
        }
    })
    .catch(error => {
        console.error('保存用户失败:', error);
        CFS.utils.showNotification('保存用户失败', 'error');
    })
    .finally(() => {
        CFS.utils.showLoading(false);
    });
}

// 查看用户详情
function viewUser(userId) {
    fetch(`/settings/ajax/users/${userId}/detail/`)
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            renderUserDetail(data.user);
            
            const modal = new bootstrap.Modal(document.getElementById('userDetailModal'));
            modal.show();
        }
    })
    .catch(error => {
        console.error('加载用户详情失败:', error);
    });
}

// 渲染用户详情
function renderUserDetail(user) {
    const content = document.getElementById('user-detail-content');
    
    content.innerHTML = `
        <div class="row g-3">
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h6 class="mb-0">基本信息</h6>
                    </div>
                    <div class="card-body">
                        <table class="table table-sm">
                            <tr><td>用户名:</td><td>${user.username}</td></tr>
                            <tr><td>邮箱:</td><td>${user.email}</td></tr>
                            <tr><td>姓名:</td><td>${user.full_name || '-'}</td></tr>
                            <tr><td>电话:</td><td>${user.phone || '-'}</td></tr>
                            <tr><td>部门:</td><td>${user.department || '-'}</td></tr>
                        </table>
                    </div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h6 class="mb-0">账户状态</h6>
                    </div>
                    <div class="card-body">
                        <table class="table table-sm">
                            <tr><td>角色:</td><td><span class="badge bg-${user.role === 'admin' ? 'warning' : 'secondary'}">${user.role === 'admin' ? '管理员' : '普通用户'}</span></td></tr>
                            <tr><td>状态:</td><td><span class="badge bg-${getStatusColor(user.status)}">${getStatusText(user.status)}</span></td></tr>
                            <tr><td>在线状态:</td><td>${user.is_online ? '<i class="fas fa-circle text-success"></i> 在线' : '<i class="fas fa-circle text-secondary"></i> 离线'}</td></tr>
                            <tr><td>最后登录:</td><td>${user.last_login || '从未登录'}</td></tr>
                            <tr><td>创建时间:</td><td>${user.created_at}</td></tr>
                        </table>
                    </div>
                </div>
            </div>
            <div class="col-12">
                <div class="card">
                    <div class="card-header">
                        <h6 class="mb-0">权限列表</h6>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            ${user.permissions.map(permission => `
                                <div class="col-md-3">
                                    <span class="badge bg-primary">${getPermissionText(permission)}</span>
                                </div>
                            `).join('')}
                        </div>
                    </div>
                </div>
            </div>
            ${user.notes ? `
                <div class="col-12">
                    <div class="card">
                        <div class="card-header">
                            <h6 class="mb-0">备注</h6>
                        </div>
                        <div class="card-body">
                            <p class="mb-0">${user.notes}</p>
                        </div>
                    </div>
                </div>
            ` : ''}
        </div>
    `;
    
    currentUserId = user.id;
}

// 获取权限文本
function getPermissionText(permission) {
    const texts = {
        'upload': '文件上传',
        'download': '文件下载',
        'create_template': '创建模板',
        'edit_template': '编辑模板',
        'delete_template': '删除模板',
        'view_logs': '查看日志',
        'manage_users': '用户管理',
        'system_settings': '系统设置'
    };
    return texts[permission] || permission;
}

// 从详情页编辑用户
function editUserFromDetail() {
    // 关闭详情模态框
    const detailModal = bootstrap.Modal.getInstance(document.getElementById('userDetailModal'));
    detailModal.hide();
    
    // 打开编辑模态框
    setTimeout(() => {
        editUser(currentUserId);
    }, 300);
}

// 切换密码显示
function togglePassword() {
    const passwordField = document.getElementById('password');
    const toggleIcon = document.getElementById('password-toggle-icon');
    
    if (passwordField.type === 'password') {
        passwordField.type = 'text';
        toggleIcon.className = 'fas fa-eye-slash';
    } else {
        passwordField.type = 'password';
        toggleIcon.className = 'fas fa-eye';
    }
}

// 重置用户密码
function resetUserPassword(userId) {
    if (!confirm('确定要重置该用户的密码吗？')) {
        return;
    }
    
    CFS.utils.showLoading(true);
    
    fetch(`/settings/ajax/users/${userId}/reset-password/`, {
        method: 'POST',
        headers: {
            'X-CSRFToken': CFS.utils.getCsrfToken()
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            CFS.utils.showNotification('密码重置成功，新密码已发送到用户邮箱', 'success');
        } else {
            CFS.utils.showNotification(data.message || '密码重置失败', 'error');
        }
    })
    .catch(error => {
        console.error('重置密码失败:', error);
        CFS.utils.showNotification('重置密码失败', 'error');
    })
    .finally(() => {
        CFS.utils.showLoading(false);
    });
}

// 切换用户状态
function toggleUserStatus(userId, currentStatus) {
    const newStatus = currentStatus === 'active' ? 'inactive' : 'active';
    const action = newStatus === 'active' ? '启用' : '停用';
    
    if (!confirm(`确定要${action}该用户吗？`)) {
        return;
    }
    
    CFS.utils.showLoading(true);
    
    fetch(`/settings/ajax/users/${userId}/toggle-status/`, {
        method: 'POST',
        body: JSON.stringify({ status: newStatus }),
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': CFS.utils.getCsrfToken()
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            CFS.utils.showNotification(`用户${action}成功`, 'success');
            loadUsers(currentPage);
            loadUserStats();
        } else {
            CFS.utils.showNotification(data.message || `用户${action}失败`, 'error');
        }
    })
    .catch(error => {
        console.error('切换用户状态失败:', error);
        CFS.utils.showNotification('操作失败', 'error');
    })
    .finally(() => {
        CFS.utils.showLoading(false);
    });
}

// 删除用户
function deleteUser(userId) {
    if (!confirm('确定要删除该用户吗？此操作不可逆！')) {
        return;
    }
    
    CFS.utils.showLoading(true);
    
    fetch(`/settings/ajax/users/${userId}/delete/`, {
        method: 'DELETE',
        headers: {
            'X-CSRFToken': CFS.utils.getCsrfToken()
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            CFS.utils.showNotification('用户删除成功', 'success');
            loadUsers(currentPage);
            loadUserStats();
        } else {
            CFS.utils.showNotification(data.message || '用户删除失败', 'error');
        }
    })
    .catch(error => {
        console.error('删除用户失败:', error);
        CFS.utils.showNotification('删除用户失败', 'error');
    })
    .finally(() => {
        CFS.utils.showLoading(false);
    });
}

// 全选/取消全选
function toggleSelectAll() {
    const selectAll = document.getElementById('select-all-users');
    const checkboxes = document.querySelectorAll('.user-checkbox');
    
    checkboxes.forEach(checkbox => {
        checkbox.checked = selectAll.checked;
    });
    
    updateSelectedUsers();
}

// 更新选中的用户
function updateSelectedUsers() {
    selectedUsers.clear();
    
    document.querySelectorAll('.user-checkbox:checked').forEach(checkbox => {
        selectedUsers.add(parseInt(checkbox.value));
    });
    
    // 更新全选状态
    const selectAll = document.getElementById('select-all-users');
    const checkboxes = document.querySelectorAll('.user-checkbox');
    const checkedCount = document.querySelectorAll('.user-checkbox:checked').length;
    
    selectAll.checked = checkedCount === checkboxes.length && checkboxes.length > 0;
    selectAll.indeterminate = checkedCount > 0 && checkedCount < checkboxes.length;
    
    // 显示/隐藏批量操作按钮
    toggleBatchActions();
}

// 切换批量操作按钮
function toggleBatchActions() {
    // 这里可以添加批量操作按钮的显示/隐藏逻辑
    if (selectedUsers.size > 0) {
        // 显示批量操作按钮
        console.log(`已选择 ${selectedUsers.size} 个用户`);
    }
}

// 清除过滤器
function clearFilters() {
    document.getElementById('search-users').value = '';
    document.getElementById('filter-role').value = '';
    document.getElementById('filter-status').value = '';
    document.getElementById('sort-by').value = 'created_at';
    
    loadUsers();
}

// 导出用户
function exportUsers() {
    const params = new URLSearchParams({
        search: document.getElementById('search-users').value,
        role: document.getElementById('filter-role').value,
        status: document.getElementById('filter-status').value,
        sort: document.getElementById('sort-by').value
    });
    
    window.open(`/settings/ajax/users/export/?${params}`);
}

// 刷新用户列表
function refreshUsers() {
    loadUsers(currentPage);
    loadUserStats();
}

// 防抖函数
function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}
</script>
{% endblock %}